package jiandian;

import java.util.Arrays;

/**
 * 颜色排序
 *
 * @author: luolidong
 * @create: 2021-07-10 10:43
 * @version: 1.0
 */
public class Demo5 {
    public void sortColors(int[] nums) {
        int l=0,r=nums.length-1;
        int i=0;
        //当i遍历到r时结束
        while (i<nums.length&&i<r){
            if(nums[i]==0){
                swap(nums, i,l++);
                i++;
            }else if(nums[i]==2){
                swap(nums, i,r--);
            }else {
                i++;
            }
        }
    }
    public void swap(int[] nums,int l,int r){
        int temp=nums[l];
        nums[l]=nums[r];
        nums[r]=temp;
    }

    public static void main(String[] args) {
        int[] nums=new int[]{1,0,1,2,1,0,2};
        new Demo5().sortColors(nums);
        System.out.println(Arrays.toString(nums));

    }
}
